package com.iflytek.springboot_medicine.service;

import com.iflytek.springboot_medicine.entity.Order;
import com.iflytek.springboot_medicine.entity.OrderItem;
import com.iflytek.springboot_medicine.repository.OrderRepository;
import com.iflytek.springboot_medicine.repository.OrderItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private OrderItemRepository orderItemRepository;
    
    @Transactional
    public Order createOrder(Order order, List<OrderItem> orderItems) {
        // 设置订单初始状态为未支付
        order.setOrderStatus(0);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        
        // 保存订单
        Order savedOrder = orderRepository.save(order);
        
        // 保存订单项
        for (OrderItem item : orderItems) {
            item.setOrderId(savedOrder.getId());
            orderItemRepository.save(item);
        }
        
        return savedOrder;
    }
    
    public List<Order> getOrdersByUserName(String userName) {
        return orderRepository.findByUserName(userName);
    }
    
    public List<Order> getOrdersByStatus(Integer status) {
        return orderRepository.findByOrderStatus(status);
    }
    
    public List<Order> getOrdersByDateRange(Date startDate, Date endDate) {
        return orderRepository.findByDateRange(startDate, endDate);
    }
    
    public List<OrderItem> getOrderItems(Long orderId) {
        return orderItemRepository.findByOrderId(orderId);
    }
    
    @Transactional
    public void updateOrderStatus(Long orderId, Integer status) {
        Optional<Order> orderOpt = orderRepository.findById(orderId);
        if (orderOpt.isPresent()) {
            Order order = orderOpt.get();
            order.setOrderStatus(status);
            order.setUpdateTime(new Date());
            orderRepository.save(order);
        }
    }
    
    @Transactional
    public void deleteOrder(Long orderId) {
        // 先删除订单项
        orderItemRepository.deleteByOrderId(orderId);
        // 再删除订单
        orderRepository.deleteById(orderId);
    }
} 